/**
 * Created by zhangyida on 15/12/29.
 */
'use strict';

import {
    View,
    TouchableOpacity,
    Navigator,
    Text,
    Image,
    StyleSheet,
    ListView,
    SegmentedControlIOS,
    ScrollView,
    TouchableHighlight,
    AlertIOS,
    ActivityIndicator
} from 'react-native';
import React from 'react';
import URL from '../config/server';
import {Utils} from '../config/utils';
import {Key} from '../config/key';
import Footer from '../component/Footer';
import Icon from 'react-native-vector-icons/Ionicons';


const NavigationBarRouteMapper = {
    LeftButton(route, navigator, index, navState) {
        return (
            <TouchableOpacity style={{flex: 1, justifyContent: 'center'}}
                              onPress={() => navigator.parentNavigator.replace({ id: 'PortfolioManage'})}>
                <Text style={{color: 'white', marginLeft: 10,fontSize:16}}>
                    管理
                </Text>
            </TouchableOpacity>
        );
    },
    RightButton(route, navigator, index, navState) {
        return null;
    },

    Title(route, navigator, index, navState) {
        return (
            <Text style={styles.navTitle}>
                自选
            </Text>
        );
    }
};


class Total extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            total0: '',
            num0: '',
            per0: '',
            total1: '',
            num1: '',
            per1: ''
        };
    }

    componentWillMount() {
        this._fetchTotal();
        this.refreshData2 = setInterval(()=> {
            this._fetchTotal();
        }, 60000)
    }
    componentWillUnmount(){
        clearInterval(this.refreshData2);
    }
    _fetchTotal() {
        let that = this;
        const TOTAL = URL.local + 'stockzonghe';
        Utils.get(TOTAL, function (data) {
            that.setState({
                total0: data[0][0],
                num0: data[0][1],
                per0: data[0][2],
                up0: data[0][1] > 0,
                total1: data[1][0],
                num1: data[1][1],
                per1: data[1][2],
                up1: data[1][1] > 0
            })

        })
    }

    render() {
        return (
            <View style={styles.total}>
                <View style={[styles.totalItem,{marginRight:4}]}>
                    <Text style={styles.totalName}>
                        上证指数
                    </Text>
                    <Text style={[styles.totalAll,{color:this.state.up0?'#ff0000':'#00fd00'}]}>
                        {this.state.up0 ? '▲' : '▼' } {this.state.total0}
                    </Text>
                    <View style={styles.totalTwo}>
                        <Text style={[styles.totalNum,{color:this.state.up0?'#ff0000':'#00fd00'}]}>
                            {this.state.num0}
                        </Text>
                        <Text style={[styles.totalNum,{color:this.state.up0?'#ff0000':'#00fd00'}]}>
                            {this.state.per0}
                        </Text>
                    </View>
                </View>
                <View style={styles.totalItem}>
                    <Text style={styles.totalName}>
                        深证指数
                    </Text>
                    <Text style={[styles.totalAll,{color:this.state.up1?'#ff0000':'#00fd00'}]}>
                        {this.state.up1 ? '▲' : '▼' }{ this.state.total1}
                    </Text>
                    <View style={styles.totalTwo}>
                        <Text style={[styles.totalNum,{color:this.state.up1?'#ff0000':'#00fd00'}]}>
                            {this.state.num1}
                        </Text>
                        <Text style={[styles.totalNum,{color:this.state.up1?'#ff0000':'#00fd00'}]}>
                            {this.state.per1}
                        </Text>
                    </View>
                </View>
            </View>
        );
    }
}

class Refresh extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            angle: new Animated.Value(0)
        }
    }

    _refresh() {
        var TIMES = 1;
        this.state.angle.setValue(0);
        this._anim = Animated.timing(this.state.angle, {
            toValue: 360 * TIMES,
            duration: 800 * TIMES,
            easing: Easing.linear
        }).start(this._animate);
        console.log(this.props.that);
        this.props.that.props.navigator.replace({
            id:'Mrzt'
        })
    }

    render() {
        return (
            <TouchableOpacity style={styles.refresh} onPress={this._refresh.bind(this)} underColor="#ffffff">
                <Animated.View style={{
                transform: [
                {rotate: this.state.angle.interpolate({
                  inputRange: [0, 360],
                  outputRange: ['0deg', '360deg']
                })}]}}>
                    <Icon name="refresh" size={40} style={{height:40,width:40,alignSelf:'center',textAlign:'center'}}
                          color="#ffffff"/>
                </Animated.View>
            </TouchableOpacity>
        );
    }
}

export default class Portfolio extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2
            }),
            loaded: 0,
            loadMore: true,
            pagesize: 10
        };
    }

    componentDidMount() {
        this.fetchData();
        console.log("第一次加载！！");
        this.refreshData = setInterval(()=> {
            this.fetchData();
        }, 60000)
    }


    componentWillUnmount() {
        console.log('组件卸载了!!');
        clearInterval(this.refreshData);
    }


    fetchData() {
        let that = this;
        console.log('获取portfolio数据');
        if(Key.username==''){
            var PORTFOLIO = URL.local + 'zixuanInfos/0/';
        }else{
            var PORTFOLIO = URL.local + 'zixuanInfos/' + Key.username + '/';
        }
        console.log(PORTFOLIO);
        Utils.get(PORTFOLIO, function (data) {
            console.log(data.length);
            //data.length=0;
            if (data.length > 0) {
                that.setState({
                    dataSource: that.state.dataSource.cloneWithRows(data),
                    loaded: 2
                })
            } else {
                that.setState({
                    loaded: 1
                })
            }
        })
    }

    _renderFooter() {
        if (this.state.loadMore) {
            return (
                <View style={styles.footerload}>
                    <ActivityIndicator
                        animating={true}
                        style={{justifyContent:'center'}}
                    />
                    <Text>
                        加载数据...
                    </Text>
                </View>
            )
        }
    }

    renderNoData() {
        return (
            <View style={styles.container}>
                <Total/>
                <View style={styles.listView}>
                    <Text style={styles.centerText}>
                        暂无自选股,请点击左上方管理添加.
                    </Text>
                </View>
                <View style={styles.down}>
                    <Footer navigator={this.props.navigator} current={'Portfolio'}/>
                </View>
            </View>
        );
    }


    _renderHeader() {
        return (
            <View style={styles.th}>
                <Text style={[styles.thText,{flex:4}]}>代码</Text>
                <Text style={[styles.thText,{flex:4}]}>名称</Text>
                <Text style={[styles.thText,{flex:3}]}>最新</Text>
                <Text style={[styles.thText,{flex:3}]}>涨幅</Text>
                <Text style={[styles.thText,{flex:3}]}>涨跌</Text>
                <Text style={[styles.thText,{flex:4}]}>总手</Text>
                <Text style={[styles.thText,{flex:4}]}>金额</Text>
                <Text style={[styles.thText,{flex:3}]}>最高</Text>
                <Text style={[styles.thText,{flex:3}]}>最低</Text>
                <Text style={[styles.thText,{flex:3}]}>换手</Text>
                <Text style={[styles.thText,{flex:3}]}>市盈</Text>
                <Text style={[styles.thText,{flex:3}]}>总市值</Text>
                <Text style={[styles.thText,{flex:4}]}>流通市值</Text>
            </View>
        );
    }

    renderScene() {
        if (this.state.loaded == 0) {
            return this.renderLoadingView();
        } else if (this.state.loaded == 1) {
            return this.renderNoData();
        } else {
            return (
                <View style={styles.container}>
                    <View style={styles.up}>
                        <Total/>
                        <ScrollView 
                            contentContainerStyle={[styles.contentView,{width:1000}]} 
                            horizontal={true}
                            bounces={false}>
                            <ListView
                                dataSource={this.state.dataSource}
                                renderHeader={this._renderHeader.bind(this)}
                                renderRow={this.renderMovie.bind(this)}
                            />
                        </ScrollView>
                    </View>
                    <View style={styles.down}>
                        <Footer navigator={this.props.navigator} current={'Portfolio'}/>
                    </View>
                </View>
            );
        }

    }

    renderLoadingView() {
        return (
            <View style={styles.container}>
                <Total/>
                <View style={styles.up}>
                    <View style={styles.listView}>
                        <Text style={styles.centerText}>
                            正在加载数据,请稍后...
                        </Text>
                    </View>
                </View>
                <View style={styles.down}>
                    <Footer navigator={this.props.navigator} current={'Portfolio'}/>
                </View>
            </View>
        );
    }


    _toContent(code) {
        const CONTENT = URL.local + 'stockInfo/' + code;
        this.props.navigator.push({
            id: 'WebContent',
            message: CONTENT
        })
    }

    renderMovie(item) {
        return (
            <TouchableOpacity onPress={()=>{this._toContent(item.code)}}>
                <View style={styles.Items}>
                    <Text style={styles.mtitle}>{item.code}</Text>
                    <Text style={styles.mtitle}>{item.name}</Text>
                    <Text style={styles.title}>{item.data0}</Text>
                    <Text style={styles.title}>{item.data1}</Text>
                    <Text style={styles.title}>{item.data2}</Text>
                    <Text style={styles.mtitle}>{item.data3}</Text>
                    <Text style={styles.mtitle}>{item.data4}</Text>
                    <Text style={styles.title}>{item.data5}</Text>
                    <Text style={styles.title}>{item.data6}</Text>
                    <Text style={styles.title}>{item.data7}</Text>
                    <Text style={styles.title}>{item.data8}</Text>
                    <Text style={styles.title}>{item.data9}</Text>
                    <Text style={styles.mtitle}>{item.data10}</Text>
                </View>
            </TouchableOpacity>
        );
    }

    render() {
        return (
            <Navigator
                renderScene={this.renderScene.bind(this)}
                navigator={this.props.navigator}
                message={this.props.message}
                navigationBar={
                    <Navigator.NavigationBar
                        style={{backgroundColor: '#e02820', alignItems: 'center'}}
                        routeMapper={NavigationBarRouteMapper}/>
                }
            />
        );
    }
}

const styles = StyleSheet.create({
    container: {
        marginTop: 64,
        flex: 1,
        backgroundColor: '#ffffff'
    },
    newstitle: {
        marginTop: 5,
        height: 30,
        width: 200
    },
    navTitle: {
        color: 'white',
        margin: 10,
        fontSize: 20,
    },
    search: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingRight: 10
    },
    Items: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        padding: 10,
        backgroundColor: '#f5f5f9',
        borderBottomWidth: 0.5,
        borderColor: '#dddddd'
    },
    footerload: {
        height: 30,
        justifyContent: 'center',
        alignItems: 'center',
        flexDirection: 'row'
    },
    contentView: {
        flex: 12,
        backgroundColor: '#f5f5f9'
    },
    listView: {
        flex: 12,
        paddingTop: 20,
        backgroundColor: '#f5f5f9',
        justifyContent: 'center',
        alignItems: 'center'
    },
    up: {
        flex: 1
    },
    down: {
        height: 44,
        backgroundColor: '#000000',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center'
    },
    bottomText: {
        flex: 1,
        color: '#ffffff',
        textAlign: 'center',
        fontSize: 16
    },
    rightContainer: {
        flex: 1,
        height: 70,
        justifyContent: 'flex-start'
    },
    title: {
        flex: 3,
        fontSize: 14,
        textAlign: 'center'
    },
    mtitle: {
        flex: 4,
        fontSize: 14,
        textAlign: 'center'
    },
    delete: {
        flex: 3
    },
    thumbnail: {
        width: 100,
        height: 70,
        marginRight: 3,
        resizeMode: Image.resizeMode.stretch
    },
    searchBar: {
        position:'relative',
        padding: 10,
        paddingLeft: 8,
        backgroundColor: "#f5f5f9",
        flexDirection: 'row',
        alignItems: 'center'
    },
    searchInput: {
        borderWidth: 0.5,
        borderColor: "#000000",
        borderRadius: 5,
        fontSize: 15,
        flex: 10,
        height: 30,
        paddingLeft:30
    },
    searchIcon: {
        alignSelf: 'center',
        textAlign: 'center',
        position:'absolute',
        left:15,
        top:15,
    },
    spinner: {
        width: 30
    },
    separator: {
        height: 1,
        backgroundColor: '#eeeeee'
    },
    refresh: {
        position: 'absolute',
        right: 10,
        bottom: 10,
        width: 46,
        paddingLeft: 7,
        paddingTop: 3,
        height: 45,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 5,
        backgroundColor: 'rgba(0, 0, 0, 0.5)'
    },
    th: {
        flexDirection: 'row',
        backgroundColor: "#000000",
        height: 30,
        justifyContent: "center",
        alignItems: 'center',
        padding: 10
    },
    thText: {
        flex: 1,
        borderRightWidth: 0.5,
        borderColor: '#dddddd',
        textAlign: 'center',
        fontSize: 16,
        color: '#ffffff'
    },
    centerText: {
        fontSize: 18
    },
    total:{
        height:70,
        backgroundColor:'#000',
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center'
    },
    totalItem:{
        flex:1,
        backgroundColor:'#292929',
        paddingTop:5,
        paddingBottom:5,
    },
    totalName:{
        flex:1,
        fontSize:16,
        color:'#ffffff',
        textAlign:'center'
    },
    totalAll:{
        flex:1,
        fontSize:19,
        color:"#ffffff",
        textAlign:'center'
    },
    totalTwo:{
        flex:1,
        flexDirection:'row',
    },
    totalNum:{
        flex:1,
        color:"#ffffff",
        fontSize:12,
        textAlign:'center',
        margin:3
    }

});